import DeliverApi from '../../../common/api/breedsales/deliverbills.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import { Select2Page } from "../../../common/serve-request.js";

let _ownOrgs = [], _levelType = [], getMainMessage = [], getEntryInfo = [], _personOrg = [], _pickerTime
let _vm, saleOrgsinfo, renderEntryInfo = [];
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening">
<div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
</div>
</div>`;

    $(function () {
        _vm = new Vue({
            el: "#order-form",
            data() {
                return {
                    "bizDate": "",
                    "saleOrgId": "",
                    "saleOrgName": "",
                    "salePerId": "",
                    "salePerName": "",
                    "salePerNumCode": "",
                    "salePerPhone": "",
                    "cstmId": "",
                    "cstmName": "",
                    "cstmNumCode": "",
                    "cstmPhone": "",
                    "totalCount": 0,
                    "remark": "",
                    "attaches": "",
                    "entries": [

                    ],
                    uploadCount: 0,
                    images: [],///处理weui自带上传插件回显重新上传时的问题
                    attaches: [],
                    datas: []
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        saleOrgs()
        uploadInit();
        _datetimePickerInit();
        _deliveryPickerInit();
        clickFun()
    });

    // 初始化数据
    const _initCommand = async () => {
        //初始化员工
        Select2Page($(`#salePerId`), `${Utils.CurDomain.EmployeeMgtUrl}/emplrecds/by/q`, (params) => {
            return ({
                SearchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            placeholder: '请选择销售员...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}(${res.numCode})`;
            }
        });
        $("#salePerId").setSelectValue();
        //客户初始化
        Select2Page($(`#cstmId`), `${Utils.CurDomain.MasterDataUrl}/yycustomers/by/q`, (params) => {
            return ({
                SearchInfo: params.term,
                pageSize: 10,
                pageIndex: (params.page || 1) - 1
            })
        }, "GET", {
            placeholder: '请选择客户...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}(${res.numCode})`;
            }
        });
        $("#cstmId").setSelectValue();

        //销售品类
        let type = await requestDict(DictionaryType.LEVEL_TYPE);
        _levelType = type.data;

        //查信息询登录用户拥有的组织
        let personOrgs = await DeliverApi.postUserOrgsList();
        personOrgs.forEach(item => {
            if (item.optTag == 1 && item.tags.indexOf('210') !== -1) {
                _personOrg.push(item.oId);
            }
        });

        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        // 渲染 分录
        if (Utils.IsNotNull(getEntryInfo)) {
            let _cost = [];
            let _num = [];
            let _weight = [];
            $.each(getEntryInfo, function (i, v) {
                _cost.push(v.unitPrice || 0);
                _num.push(v.planQty || v.count || 0);
                _weight.push(v.estimatedAvgWeight || v.weight || 0);
            });

            $('#totalCost').text(eval(_cost.join('+')));
            $('#totalNum').text(eval(_num.join('+')));
            $('#totalWeight').text(eval(_weight.join('+')));
            getEntryInfo = getEntryInfo.map(item => {
                let specLevelType = '';
                let detailDeliveryAddress = "";
                if (Utils.IsNotNull(_levelType.find(s => s.value == item.specLevel))) {
                    specLevelType = _levelType.find(s => s.value == item.specLevel).displayName;
                } else {
                    specLevelType = item.specLevel;
                }
                //收货地址
                if (Utils.IsNotNull(item.deliveryRegion)) {
                    let areaId = item.deliveryRegion.split('|');
                    let split = areaId[1].split(';');
                    detailDeliveryAddress = split[0] + split[1] + split[2] + split[3] + item.deliveryAddress
                } else {
                    detailDeliveryAddress = item.deliveryAddress;
                }
                return { ...item, specLevelType, detailDeliveryAddress }
            });
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
        }
        // 赋值 销售组织 业务日期 备注
        let datas = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        // 不为空时 赋值
        if (Utils.IsNotNull(datas)) {
            _vm.bizDate = datas.bizDate
            _vm.remark = datas.remark
            $('#saleOrgId').setSelectValue(datas.saleOrgId);
            $('#salePerId').setSelectValue(datas.salePerId, datas.salePerName);
            $('#cstmId').setSelectValue(datas.cstmId, datas.cstmName);
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            // 删除分录 删除页面数据 删除ID
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../deliverbills/deliverbills.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            $("#informationSubmit").text("保存");
            $("title").text("销售出库单 - 编辑");
            DeliverApi.getDeliverinfo(ids).then(res => {
                _vm.bizDate = (res.bizFormObj.bizDate.split(' '))[0].replace(/\//g, '-')
                _vm.saleOrgId = res.saleOrgId
                _vm.saleOrgName = res.saleOrgName
                $('#saleOrgId').setSelectValue(res.saleOrg.id);
                _vm.remark = res.remark
                // 获取分录数据
                getEntryInfo = res.entries;
                // 存分录
                res.entries.forEach((item, index) => item.seq = index + 1)
                //console.log(res.entries);
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.entries))
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.entries = res.entries.map(item => {
                    let specLevelType = '';
                    if (Utils.IsNotNull(_levelType.find(s => s.value == item.specLevel))) {
                        specLevelType = _levelType.find(s => s.value == item.specLevel).displayName;
                    } else {
                        specLevelType = item.specLevel;
                    }
                    return { ...item, specLevelType }
                });
                $('#salesEntry').empty().append(addsaleTemplate(res.entries));
            });
        }
    }

    //业务日期控件初始化
    const _datetimePickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#search-date').on('click', function (e) {
            e.stopPropagation();
            $("#search-date").picker("open");
            _pickerDate();
        });
        $("#search-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _pickerTime = '';
                    _pickerTime = value;
                }
            }
        );
    }

    //业务日期确认事件
    const _pickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#businessTime').val(_pickerTime);
            _vm.bizDate = _pickerTime
        });
    }
    // 业务日期获取当天
    const initCurrentDay = () => {
        let todayDate = moment().format('YYYY-MM-DD')
        $('#businessTime').val(todayDate)
        _vm.bizDate = todayDate
    }

    //发货日期控件初始化
    const _deliveryPickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#delivery-date').on('click', function (e) {
            e.stopPropagation();
            $("#delivery-date").picker("open");
            _deliverypickerDate();
        });
    }

    // 初始化销售组织
    const saleOrgs = async () => {
        _ownOrgs = await DeliverApi.postUserOrgsList();
        DeliverApi.getOrgsListType().then(res => {
            let sale = res.filter(s => s.typeValue == true);
            let obj = _ownOrgs.filter(item => sale.some(item2 => item2.id == item.oId));
            $('#saleOrgId').select2({
                placeholder: '请选择销售组织...', //默认文字提示
                language: "zh-CN",//汉化
                data: obj.map(item => {
                    return {
                        id: item.oId,
                        name: item.oName,
                        numCode: item.oNumCode,
                        text: `${item.oName}(${item.oNumCode})`
                    }
                }),
            });
            $("#saleOrgId").setSelectValue();

            //解决字段过长
            $('#saleOrgId').on('change', function () {
                saleOrgsinfo = cutstr($('#select2-saleOrgId-container').text(), 22)
                $('#select2-saleOrgId-container').text(`${saleOrgsinfo}`)
                if (Utils.IsNotNull($('#saleOrgId').select2('data')[0])) {
                    _vm.saleOrgId = $('#saleOrgId').select2('data')[0].id
                    _vm.saleOrgName = $('#saleOrgId').select2('data')[0].name
                }
            });

            // $('#saleOrgId').on('select2:select', function () {
            //     getEntryInfo = [];
            //     // _initEntry();
            //     $('#totalNum').text(0);
            //     $('#totalWeight').text(0);
            // });

            if (Utils.IsNotNull(getUrlKey("id"))) {
                $("#saleOrgId").setSelectValue(_vm.saleOrgId)
                $('#saleOrgId').prop('disabled', true);
            } else {
                $("#saleOrgId").change()
            }
        }).then(_ => {
            _initCommand()
        });
    }

    const storeSession = () => {
        let datas = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        let deliver = {
            "bizDate": _vm.bizDate,
            "saleOrgId": _vm.saleOrgId,
            "saleOrgName": $(`#saleOrgId`).select2('data')[0].name,
            "saleOrgNumCode": $(`#saleOrgId`).select2('data')[0].numCode,
            "salePerId": $('#salePerId').val() || datas?.salePerId,
            "salePerName": $('#salePerId').select2('data')[0]?.name || datas?.salePerName,
            "salePerNumCode": $('#salePerId').select2('data')[0]?.numCode || datas?.salePerNumCode,
            "cstmId": $('#cstmId').select2('data')[0]?.id || datas?.cstmId,
            "cstmName": $('#cstmId').select2('data')[0]?.name || datas?.cstmName,
            "cstmNumCode": $('#cstmId').select2('data')[0]?.numCode || datas?.cstmNumCode,
            "remark": _vm.remark,
        }
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliver)
    }


    // 操作函数
    const clickFun = () => {
        // 点击分录
        $('#add-saleEntry').on("click", function (e) {
            if (!Utils.IsNotNull($('#saleOrgId').val())) {
                return $.toptip(`请先选择销售组织!`, 'warning');
            }
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0
            // console.log(index);
            location.href = `../deliverbills/entry.html?v=${Utils.GetTime()}&orgId=${_vm.saleOrgId}&index=${index}&isEdit=${false}`;
        });

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let datas = JSON.parse(Utils.GetSessionStorage("deliverDatas"));
            if (!Utils.IsNotNull($('#salePerId').val() || datas?.salePerId)) {
                return $.toptip(`请选择销售员!`, 'warning');
            }
            if (!Utils.IsNotNull($('#cstmId').val() || datas?.cstmId)) {
                return $.toptip(`请选择客户!`, 'warning');
            }
            savetips();
        });

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {

                            // 过滤
                            let datas = getEntryInfo.filter(item => item.seq != seq)

                            // 重置seq
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []

                            // 赋值 SessionStorage
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", info))
                            $('#salesEntry').empty().append(addsaleTemplate(info));
                            $.closeModal();
                        }
                    }
                ]
            });
        });

        // 编辑
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            // let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0;
            let index = $(this).data('index')
            location.href = `../deliverbills/orderentry.html?v=${Utils.GetTime()}&orgId=${_vm.saleOrgId}&index=${index}&isEdit=${true}`;
        });
    }

    //提示信息
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >是否确认保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let saveStandard = [];
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"));
                        $.each(entries, function (i, v) {
                            if (!Utils.IsNotNull(v.deiverName)) {
                                saveStandard.push(v)
                            }
                        });
                        if (saveStandard.length > 0) {
                            return $.toptip(`请先完善销售订单信息`, 'warning');
                        }

                        let _attaches = [];
                        $.each(_vm.images, function (i, v) {
                            _attaches.push(v.imageId);
                        });
                        let res = JSON.parse(Utils.GetSessionStorage("deliverDatas"));
                        let datas = {
                            "deliveryId": Utils.GetSessionStorage("ids"),
                            "bizDate": _vm.bizDate,
                            "saleOrgId": _vm.saleOrgId,
                            "saleOrgName": $(`#saleOrgId`).select2('data')[0].name,
                            "salePerId": $('#salePerId').val() || res.salePerId,
                            "salePerName": $('#salePerId').select2('data')[0]?.name || res.salePerName,
                            "salePerNumCode": $('#salePerId').select2('data')[0]?.numCode || res.salePerNumCode,
                            "salePerPhone": "",
                            "cstmId": $('#cstmId').select2('data')[0]?.id || res.cstmId,
                            "cstmName": $('#cstmId').select2('data')[0]?.name || res.cstmName,
                            "cstmNumCode": $('#cstmId').select2('data')[0]?.numCode || res.cstmNumCode,
                            "cstmPhone": "",
                            "totalCount": 0,
                            "attaches": _attaches.join(','),
                            "remark": $('#remark').val(),
                            "entries": JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
                        }

                        DeliverApi.generateDeliverBills(JSON.stringify(datas)).then(res => {
                            $.toptip('请求成功。', 'success');
                            // 延时一秒跳转  要看提示 
                            setTimeout(function () {
                                window.sessionStorage.removeItem("getEntryInfo");
                                window.sessionStorage.removeItem("deliverDatas");
                                location.href = `../deliverbills/deliverbills.html?v=${Utils.GetTime()} `;
                            }, 1000);
                        });
                    }
                }
            ]
        });
    }


    //TODO : 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter(item => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }

    /**
 *@file 附件上传
 *@create周润玉
*/
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(res => {
            if (res.isSucceed) {
                let _list = _vm.images;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: upFiles.url,
                    name: newName,
                });
                _vm.attaches.push(res.data);
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.images[i].id);
                    $(this).attr('data-image-id', _vm.images[i].imageId);
                    $(this).attr('data-name', _vm.images[i].name);
                    $(this).attr('data-suffix', _vm.images[i].type);
                    $(this).attr('data-url', _vm.images[i].url);
                    $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                $.hideLoading();
                $.closeModal();
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.uploadCount = --_vm.uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

})(window, document, jQuery)